package by.msokoloff.javaweb2015.services.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.springframework.stereotype.Service;

import by.msokoloff.javaweb2015.dataaccess.AirportDao;
import by.msokoloff.javaweb2015.datamodel.Airport;
import by.msokoloff.javaweb2015.datamodel.Airport_;
import by.msokoloff.javaweb2015.datamodel.Flight;
import by.msokoloff.javaweb2015.datamodel.Flight_;
import by.msokoloff.javaweb2015.services.AirportService;
import by.msokoloff.javaweb2015.services.FlightService;

@Service
public class AirportServiceImpl implements AirportService {

	@Inject
	private AirportDao dao;

	@Inject
	private FlightService flightService;

	@Override
	public Airport get(Integer id) {
		return dao.getById(id);
	}

	@Override
	public List<Airport> getAll() {
		return dao.getAll();
	}

	@Override
	public void createOrUpdate(Airport airport) {
		if (airport.getId() == null) {
			dao.create(airport);
		} else {
			dao.update(airport);
		}
	}

	@Override
	public void delete(Airport airport) {
		dao.delete(airport.getId());
	}

	@Override
	public void deleteAll() {
		dao.deleteAll();
	}

	@Override
	public Long getCount() {
		return dao.getCount();
	}

	@Override
	public List<Airport> getAll(SingularAttribute<Airport, ?> attr, boolean ascending, int startRecord, int pageSize) {
		return dao.getAll(attr, ascending, startRecord, pageSize);
	}

	@Override
	public List<Airport> getByField(SingularAttribute<Airport, ?> attr, Object val) {
		return dao.getByField(attr, val);
	}

	@Override
	public void deleteWithRelations(Airport airport) {
		List<Flight> relatedFlights = flightService.getByField(Flight_.departureAirport, airport);
		relatedFlights.addAll(flightService.getByField(Flight_.destinationAirport, airport));
		for (Flight flight : relatedFlights) {
			flightService.deleteWithRelations(flight);
		}
		delete(airport);
	}

	@Override
	public List<Airport> getContaining(String val, Integer max) {
		return dao.getContaining(Airport_.name, val, max);
	}
}
